package org.nf.trading.service.app.message.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nf.trading.dao.MessageMapper;
import org.nf.trading.dto.ChatMessageDTO;
import org.nf.trading.dto.MessageDTO;
import org.nf.trading.entity.Message;
import org.nf.trading.service.app.message.exception.MessageDataException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@ServerEndpoint(value = "/connect", configurator = HandShakeConfigurator.class)
//@Data
public class NotifyWebSocketServerHandler {
    @Autowired
    private MessageMapper messageMapper;

    /**
     * 用户保存所有的用户
     */
    private static Map<String,Session> clients = new HashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        //获取登录的用户
        String userId = (String)session.getUserProperties().get("userId");
        System.out.println("当前用户为：" + userId);
        clients.put(userId, session);
        clients.forEach((k,v) -> {
            System.out.println("在线用户=====> "+k);
        });
    }

    /**
     * 用户离线移除在线列表
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        String userId = (String) session.getUserProperties().get("userId");
        log.info(userId + "已离线");
        //从用户列表移除这个用户
        clients.remove(userId);
        clients.forEach((k,v) -> {
            System.out.println("离线用户=====> "+k);
        });
    }

    public void chatSend(ChatMessageDTO chatMessageDTO){
        if (clients.containsKey(chatMessageDTO.getReceiverId())) {
            chatMessageDTO.setType("2");
            // 发送消息
            try {
                String s = new ObjectMapper().writeValueAsString(chatMessageDTO);
                clients.get(chatMessageDTO.getReceiverId()).getBasicRemote().sendText(s);
            } catch (IOException e) {
                e.printStackTrace();
                throw new MessageDataException(500,"消息发送失败");
            }
        }
    }

    public void send(MessageDTO message) {
//        String receiver = message.getReceiverId()+"";
//        if (messageMapper.getMessageByProductIdIs(message.getReceiveId()) == null){
//            ArrayList<String> arrayList = new ArrayList<>();
//            arrayList.add(message.getContent());
//            try {
                //序列化json
//                message.setMessageContent(new ObjectMapper().writeValueAsString(arrayList));
//            } catch (JsonProcessingException e) {
//                throw new RuntimeException(e);
//            }
//            messageMapper.insert(message);
//        }
        if (clients.containsKey(message.getReceiveId()+"")) {

            // 发送消息
            try {
                String s = new ObjectMapper().writeValueAsString(message);
                clients.get(message.getReceiveId()+"").getBasicRemote().sendText(s);
            } catch (IOException e) {
                e.printStackTrace();
                throw new MessageDataException(500,"消息发送失败");
            }
        }
//        else {
//            System.out.println("用户不在线");
//            System.out.println("操作数据库");
//
//            //判断是否存在这个消息，不存在则修改，存在则添加
//            if (messageMapper.getMessageByProductIdIs(message.getProductId()) == null){
//                ArrayList<String> objects = new ArrayList<>();
//                objects.add(message.getMessageContent());
//                try {
//                    //序列化json
//                    message.setMessageContent(new ObjectMapper().writeValueAsString(objects));
//                } catch (JsonProcessingException e) {
//                    throw new RuntimeException(e);
//                }
//                messageMapper.insert(message);
//            }else {
//                //查到是否还有数据存在
//                Message message1 = messageMapper.getMessageByProductIdIs(message.getProductId());
//                //如果存在了，数据是json格式，需要转换，考虑到用户可能没有读取上一条信息，需要在数据末尾继续添加未读消息
//                String messageContent = message1.getMessageContent();
//                try {
//                    //序列化数据库的消息进行消息拼接
//                    ArrayList<String> arrayList = new ObjectMapper().readValue(messageContent, ArrayList.class);
//                    //添加数据
//                    arrayList.add(message.getMessageContent());
//                    //更新数据库
//                    messageMapper.updateMessageContent(message.getProductId(), new ObjectMapper().writeValueAsString(arrayList));
//                } catch (JsonProcessingException e) {
//                    throw new RuntimeException(e);
//                }
//
//            }
//        }

    }
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket 连接出现异常: {}", throwable);
        // 可以选择关闭连接等操作
        try {
            session.close();
        } catch (IOException e) {
            log.error("关闭 WebSocket 连接出现异常: {}", e.getMessage());
        }
    }

}
